/*
 * BanBu_RegisterViewController
 * @description 本文件提供登陆注册界面主界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供登陆注册界面主界面的ViewController
 */

#import "BanBu_RegisterViewController.h"
#import "SFHFKeychainUtils.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_LocationManager.h"
#import "UIDevice+Helper.h"
#import "BanBu_NavButton.h"
#import "BanBu_GoLoginViewController.h"
#import "BanBu_UserAgreement.h"
#import "BanBu_VideoAuthenViewController.h"

@interface BanBu_RegisterViewController ()
{
    BOOL agree;
}
@end

@implementation BanBu_RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)complete:(UIButton *)button
{
    NSMutableDictionary *registerInfo = [NSMutableDictionary dictionary];
    [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:Latitude];
    [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:Longitude];
//    [registerInfo setValue:[self getFacePath:[resDic valueForKey:@"smallpic"]] forKey:@"facepath"];
//    [registerInfo setValue:[self getFaceName:[resDic valueForKey:@"smallpic"]] forKey:@"facefile"];
//    [registerInfo setValue:[self getFaceName:[resDic valueForKey:@"largepic"]] forKey:@"facefull"];
    [self saveRegister:registerInfo];
    
}

#pragma mark -注册信息保存到MyAppDataManager 需要参数 “plat” “plong” “facepath” “facefile” “facefull”
-(void)saveRegister:(NSDictionary *)_registerInfo
{
    [MyAppDataManager.regDic addEntriesFromDictionary:_registerInfo];
}
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}
#pragma show and hide the keyboard
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}
#pragma mark - 双击显示当前服务器网址
-(void)handleDoubleFingerEvent:(UITapGestureRecognizer *)dtap
{
    //    [TKLoadingView showTkloadingAddedTo:self.view title:MyAppDataManager.banbuHostIP activityAnimated:NO duration:2];
    //    [TKLoadingView showTkloadingAddedTo:self.view point:self.view.center title:MyAppDataManager.banbuHostIP activityAnimated:NO duration:2];
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:self.navigationController.view.center title:MyAppDataManager.banbuHostIP activityAnimated:NO duration:2];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setUpForDismissKeyboard];

    
    UITapGestureRecognizer *doubleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                      action:@selector(handleDoubleFingerEvent:)];
    doubleFingerOne.numberOfTouchesRequired = 2;
    doubleFingerOne.numberOfTapsRequired = 2;
    doubleFingerOne.delegate = self;
    [self.view addGestureRecognizer:doubleFingerOne];
    
    _logoImageView.layer.cornerRadius = 20;
    agree = NO;
    [self checkAgreeKoochatAgreement];
    [_manButton setTitle:NSLocalizedString(@"iamboyreg", nil) forState:UIControlStateNormal];
    [_womanButton setTitle:NSLocalizedString(@"iamgirlreg", nil) forState:UIControlStateNormal];
    
    _pnameField.placeholder = [NSString stringWithFormat:@"  %@",NSLocalizedString(@"enterPname", nil)];
    _agreeStr = NSLocalizedString(@"iagree", nil);
    _koolabel.text = NSLocalizedString(@"koochatComment", nil);
    
    [_haveAccount setTitle:NSLocalizedString(@"登录", nil) forState:UIControlStateNormal];
    [self setArrtr];
    _agreeLabel.userInteractionEnabled = YES;
    _scrollview.frame = CGRectMake(0, 0, __MainScreen_Width, 568);
    _scrollview.contentSize = CGSizeMake(320, 548);
}

-(void)setArrtr
{
    NSArray *URLs;
    NSArray *URLRanges;
    NSAttributedString *as = [self attributedString:&URLs URLRanges:&URLRanges];
    
    _agreeLabel.attributedText = as;
    
    [_agreeLabel setURLs:URLs forRanges:URLRanges];
    
    _agreeLabel.URLClickHandler = ^(CXAHyperlinkLabel *label, NSURL *URL, NSRange range, NSArray *textRects){
        
        [self goToAgreement:nil];
    };
    
    CGPoint point = _agreeLabel.frame.origin;
    
    CGFloat margin = 10.;
    CGSize size = CGRectInset(CGRectMake(0, 0, _agreeLabel.frame.size.width + 10, 100), margin, margin).size;
    size.height = INT16_MAX;
    size = [_agreeLabel sizeThatFits:size];
    _agreeLabel.frame = CGRectMake(point.x+5, point.y, size.width, size.height);
    
    _agreeLabel.center = CGPointMake(_agreeLabel.center.x, _agreeLabel.center.y+5);
    
    _agreeLabel.frame = CGRectMake(_agreeLabel.frame.origin.x-5,_agreeLabel.frame.origin.y-5,_agreeLabel.frame.size.width+10,_agreeLabel.frame.size.height+10);
}

#pragma mark - privates
- (NSAttributedString *)attributedString:(NSArray *__autoreleasing *)outURLs
                               URLRanges:(NSArray *__autoreleasing *)outURLRanges
{
    NSString * HTMLText = _agreeStr;
    
    NSArray *URLs;
    NSArray *URLRanges;
    UIColor *color = [UIColor blackColor];
    UIFont *font = [UIFont fontWithName:@"Baskerville" size:16.0];
    NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
    mps.lineSpacing = ceilf(font.pointSize * .5);
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowOffset = CGSizeMake(0, 1);
    NSString *str = [NSString stringWithHTMLText:HTMLText baseURL:[NSURL URLWithString:@""] URLs:&URLs URLRanges:&URLRanges];
    
    NSMutableAttributedString *mas = [[[NSMutableAttributedString alloc] initWithString:str attributes:@
                                       {
                                           NSForegroundColorAttributeName : color,
                                           NSFontAttributeName            : font,
                                           NSParagraphStyleAttributeName  : mps,
                                           NSShadowAttributeName          : shadow,
                                       }] autorelease];
    [shadow release];
    [URLRanges enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
        [mas addAttributes:@
         {
             NSForegroundColorAttributeName : [UIColor blueColor],
             NSUnderlineStyleAttributeName  : @(NSUnderlineStyleSingle)
         } range:[obj rangeValue]];
    }];
    
    *outURLs = URLs;
    *outURLRanges = URLRanges;
    
    return [mas copy];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(void)checkAgreeKoochatAgreement
{
    agree = !agree;
    [_agreeButton setImage:[UIImage imageNamed:agree?@"agreeSelect.png":@"agreeDeselect.png"] forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(IBAction)selectSexAndRegister:(id)sender
{
//    NSString *sex = nil;
//    if(sender == _manButton)
//    {
//        sex = @"m";
//    }
//    else if(sender == _womanButton)
//    {
//        sex = @"f";
//    }
//    "Iamboy"="我是男性";
//    "Iamgirl"="我是女性";
//    "iagree"="我已阅读并同意<半圆使用条款>";
//    "koochatComment"= "半圆一下,你就不陌生!";
//    "sexRegNotice"="性别确认提示";
//    "sexConfirmNotice"="性别一但确认无法更改";
//    
//    
//    "oneStepFollow"="一键关注";
//    "myLabel"="我的标签";
//    "regWithSex"="是否以当前性别进行注册";
//    "onekeyReg"="一键注册";
    if(!agree)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"agreeFirstNotice", nil) activityAnimated:NO duration:1];
        return;
    }
    if(!_pnameField.text.length)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"enterPname", nil) activityAnimated:NO duration:1];
        return;
    }
    NSInteger sexTag = 0;
    if(sender == _manButton)
    {
//        sex = @"m";
        sexTag = 100;
    }
    else if(sender == _womanButton)
    {
//        sex = @"f";
        sexTag = 101;
    }
    
    NSString *alertString = [NSString stringWithFormat:@"%@:%@,%@",NSLocalizedString(@"sexSelect", nil),(sexTag-100)?NSLocalizedString(@"girl", nil):NSLocalizedString(@"boy", nil),NSLocalizedString(@"sexConfirmNotice", nil)];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:(sexTag-100)?NSLocalizedString(@"girlConfirmNotice", nil):NSLocalizedString(@"boyConfirmNotice", nil) message:alertString delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
    alert.tag = sexTag;
    [alert show];
    [alert release];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 88888)
    {
        if(buttonIndex == 0)
        {
            BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            delegate.logined = YES;
            [delegate setViewController:YES];
        }
        else
        {
#pragma mark - 注册，进行视频认证
            BanBu_VideoAuthenViewController *video = [[BanBu_VideoAuthenViewController alloc] initWithRegisterVerify:YES];
            [self.navigationController pushViewController:video animated:YES];
            [video release];
        }
        return;
    }
    if(buttonIndex == 1)
    {
        [self registWithSex:(alertView.tag-100)?@"f":@"m"];
    }
}
#pragma mark - 有半圆账号，跳转到登陆界面
/**
 * @函数名称：goToLoginView:
 * @函数描述：有半圆账号，跳转到登陆界面
 * @输入参数：(id)sender
 * @输出参数：
 * @返回值：
 * @author：your name
 */
- (IBAction)goToLoginView:(id)sender
{
    BanBu_GoLoginViewController *login = [[BanBu_GoLoginViewController alloc] init];
    [self.navigationController pushViewController:login animated:YES];
    [login release];

}

- (IBAction)goToAgreement:(UIButton *)sender
{
    BanBu_UserAgreement *agreement = [[BanBu_UserAgreement alloc]init];
    [self.navigationController pushViewController:agreement animated:YES];
    [agreement release];
}

- (IBAction)agreeKoochatAgreement:(UIButton *)sender
{
    [self checkAgreeKoochatAgreement];
}

#pragma mark - 选择性别注册
/**
 * @函数名称：registWithSex:
 * @函数描述：
 * @输入参数：
 * @输出参数：
 * @返回值：
 * @author：your name
 */
-(void)registWithSex:(NSString *)_sex
{
    [_pnameField resignFirstResponder];
    NSError *error;
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
    CFRelease(puuid);
    CFRelease(uuidString);
    if(![[SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error] length])
    {
        [SFHFKeychainUtils storeUsername:@"halfeet_user_UUID" andPassword:result forServiceName:@"com.halfeet_halfeet" updateExisting:YES error:&error];
    }
   
    NSLog(@"%@",_pnameField.text);
    BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
    
    
    //yinlinlin 2014年08月08日15:24:12 先使用pushid，获取不到的情况下使用systemUDID
    NSString *systemUDID;
    if(ap.pushid&&ap.pushid.length)
    {
        systemUDID = ap.pushid ;
    }
    else
    {
        systemUDID = [SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error];
    
    }
    
    NSString *jsonName = [[_pnameField.text dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    NSDictionary *registerInfo = [NSDictionary dictionaryWithObjectsAndKeys:systemUDID,@"deviceid",_sex,@"gender",jsonName,@"pname_b64",ap.pushid,@"pushid",nil];
//
//    [_registerInfo setValue:systemUDID forKey:@"deviceid"];
    
    //    srand((unsigned)time(0));
    //    [_registerInfo setValue:[NSString stringWithFormat:@"%d",rand()] forKey:@"deviceid"];
    
//    NSLog(@"%@",registerInfo);
    [AppComManager getBanBuData:BanBu_Set_Register_User_Onekey par:registerInfo delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"registering", nil) activityAnimated:YES];

}
- (void)dealloc
{
    [_manButton release];
    [_womanButton release];
    [_agreeButton release];
    [_agreeLabel release];
    [_commenLabel release];
    [_logoImageView release];
    [_koolabel release];
    [_haveAccount release];
    [_pnameField release];
    [_scrollview release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setManButton:nil];
    [self setWomanButton:nil];
    [self setAgreeButton:nil];
    [self setAgreeLabel:nil];
    [self setCommenLabel:nil];
    [self setLogoImageView:nil];
    [self setKoolabel:nil];
    [self setHaveAccount:nil];
    [self setPnameField:nil];
    [self setScrollview:nil];
    [super viewDidUnload];
}
- (void)login:(NSDictionary *)_loginDic
{
    [AppComManager getBanBuData:BanBu_Check_Login par:_loginDic delegate:self];
}
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    NSLog(@"registerDic : %@",resDic);
    NSLog(@"registerERROR :%@",error);
    [UserDefaults setValue:[resDic valueForKey:@"initpassword"] forKey:@"Pwd"];
    [UserDefaults synchronize];
    
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0.0];
    if(error)
    {
        if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_Avatar]){
            
            UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"uploadFailNotice", nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"reUpload", nil), nil];
            alert.tag = 1;
            [alert show];
            [alert release];
            return;
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Register_User_Onekey])
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"network_error", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"retry", nil), nil];
            [alert show];
            alert.tag = 111;
            [alert release];
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Check_Login])
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"network_error", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"retry", nil), nil];
            [alert show];
            alert.tag = 222;
            [alert release];
        }
        else if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        
        
        return;
    }
    
//    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_Avatar]){
//        if([[resDic valueForKey:@"ok"] boolValue])
//        {
//            
//            NSMutableDictionary *registerInfo = [NSMutableDictionary dictionary];
//            [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:Latitude];
//            [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:Longitude];
//            [registerInfo setValue:[self getFacePath:[resDic valueForKey:@"smallpic"]] forKey:@"facepath"];
//            [registerInfo setValue:[self getFaceName:[resDic valueForKey:@"smallpic"]] forKey:@"facefile"];
//            [registerInfo setValue:[self getFaceName:[resDic valueForKey:@"largepic"]] forKey:@"facefull"];
//            [self saveRegister:registerInfo];
//            
//            //弹出UIAlertView  点击确定进行登录操作
//            UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"sysAvatarNotice", nil) message:NSLocalizedString(@"sysNoticeaaa", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
//            alert.tag = 2;
//            [alert show];
//            [alert release];
//            
//        }else{
//            [TKLoadingView showTkloadingAddedTo:self.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:2.0];
//        }
//    }
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Register_User_Onekey]){
        NSLog(@"%@",resDic);
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            NSMutableDictionary *loginDic = [NSMutableDictionary dictionary];
            [loginDic setValue:[resDic valueForKey:@"userid"] forKey:@"email"];
            [loginDic setValue:@"" forKey:@"pass"];
            [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:@"plat"];
            [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:@"plong"];
            [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"regby"] forKey:@"regby"];
            
            BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            [loginDic setValue:delegate.pushid forKey:@"pushid"];
            
            NSString *isJailbroken = nil;
            if([[UIDevice currentDevice] isJailbroken]){
                isJailbroken = @"YES";
            }else{
                isJailbroken = @"NO";
            }
            
            NSError *error;
            CFUUIDRef puuid = CFUUIDCreate( nil );
            CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
            NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
            CFRelease(puuid);
            CFRelease(uuidString);
            if(![[SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error] length])
            {
                [SFHFKeychainUtils storeUsername:@"halfeet_user_UUID" andPassword:result forServiceName:@"com.halfeet_halfeet" updateExisting:YES error:&error];
            }
            
            [result release];
            NSString *systemUDID = [SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error];
            [loginDic setValue:[NSString stringWithFormat:@"%@::%@::%@::%@::%@::%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion],[MyAppDataManager getPreferredLanguage],[[UIDevice currentDevice] platformString],isJailbroken,systemUDID] forKey:@"sysparam"];
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:[[UIDevice currentDevice] systemVersion] forKey:@"osver"];
            NSString *deviceStr = [[UIDevice currentDevice] platformString];
            NSString *dev = nil;
            NSString *isp = nil;
            if([deviceStr rangeOfString:@"("].location != NSNotFound&&[deviceStr rangeOfString:@")"].location != NSNotFound)
            {
                isp = [deviceStr substringFromIndex:[deviceStr rangeOfString:@"("].location];
                dev = [deviceStr substringToIndex:[deviceStr rangeOfString:@"("].location];
            }
            //    NSLog(@"%@ %@",isp,dev);
            [dic setValue:isp forKey:@"isp"];
            [dic setValue:dev forKey:@"dev"];
            
            [dic setValue:[[UIDevice currentDevice] name] forKey:@"name"];
            [dic setValue:isJailbroken forKey:@"jail"];
            [loginDic setValue:dic forKey:@"phoneinfor"];
            
            
            [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
            //yinlinlin 2014年08月08日15:24:12 先使用pushid，获取不到的情况下使用systemUDID
            BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            
            if(ap.pushid&&ap.pushid.length)
            {
                [loginDic setValue:ap.pushid forKey:@"deviceid"];
            }
            else
            {
                [loginDic setValue:systemUDID forKey:@"deviceid"];
            }

            
            NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
            [loginDic setValue:version forKey:@"version"];
            [self login:loginDic];
            
            
            self.navigationController.view.userInteractionEnabled = NO;
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"getMessage", nil) activityAnimated:YES];
        }
        else
        {
            if([[resDic allKeys] indexOfObject:@"error"] != NSNotFound)
            {
                UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"sysNotice", nil) message:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
                alert.tag = 1231412;
                [alert show];
                [alert release];
            }
        }
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Check_Login]){
        
        
        if([[resDic valueForKey:@"ok"]boolValue]){
            
            [UserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"isDefaultKey"];//用户用的是默认密码
            [UserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"isNewRegister"];//新注册用户
            
            MyAppDataManager.loginid = [resDic valueForKey:@"loginid"];
            MyAppDataManager.useruid = [resDic valueForKey:@"userid"];
            MyAppDataManager.userAvatar =[resDic valueForKey:@"uface"];
            //创建10张聊天记录表
            [MyAppDataManager initDetailChatMessageTable];
            [UserDefaults setValue:resDic forKey:MyAppDataManager.useruid];
            
            if(![[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]){
                NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithCapacity:2];
                [settingsDic setValue:[NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES], nil] forKey:@"boolKey"];
                [settingsDic setValue:@"msg_1" forKey:@"MusicSwith"];
                [settingsDic setValue:@"send_0" forKey:@"sendMsgBoolKey"];//添加发消息声音提示
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"systemset_friendreadstatus"];//发送消息已读状态设置
                [settingsDic setValue:[NSNumber numberWithBool:NO] forKey:@"setFollowsHidden"];//隐藏关注的人，默认为否，不隐藏
                
                [settingsDic setValue:[resDic valueForKey:@"hideme"] forKey:@"hideme"];
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"visitYouNotification"];   //接收“我查看了你的个人资料”通知
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"followYouNotification"];  //接收“我关注了你”通知
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"takeCareNotification"];   //接收新用户注册通知
                [settingsDic setValue:[NSNumber numberWithBool:1] forKey:@"onceRun"];
                //保存当前本版号
                NSString  *versonPath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"data.dat"];
                NSMutableDictionary * versonDic = [NSKeyedUnarchiver unarchiveObjectWithFile:versonPath];
                NSString * versonString = MyAppDataManager.newVersionNumber;
                versonString = [versonString stringByReplacingOccurrencesOfString:@"." withString:@""];
                [versonDic setValue:versonString forKey:MyAppDataManager.useruid];
                NSData *listData=[NSKeyedArchiver archivedDataWithRootObject:versonDic];
                [listData writeToFile:versonPath atomically:YES];
                
                NSMutableDictionary *addDic = [NSMutableDictionary dictionaryWithDictionary:resDic];
                [addDic setValue:settingsDic forKey:@"settings"];
                [UserDefaults setValue:addDic forKey:MyAppDataManager.useruid];
            }
            else
            {
                NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
                [settingsDic setValue:[resDic valueForKey:@"hideme"] forKey:@"hideme"];
                NSMutableDictionary *addDic = [NSMutableDictionary dictionaryWithDictionary:resDic];
                [addDic setValue:settingsDic forKey:@"settings"];
                [UserDefaults setValue:addDic forKey:MyAppDataManager.useruid];
            }
            [UserDefaults setValue:MyAppDataManager.useruid forKey:@"myID"];
            [UserDefaults synchronize];
            
            if([[MyAppDataManager.regDic valueForKey:@"regby"]isEqualToString:@"b"]){
                NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithCapacity:2];
                if([[MyAppDataManager.regDic valueForKey:@"bindtype"]integerValue] == 2){
                    [pars setValue:@"twitter" forKey:@"bindto"];
                    [pars setValue:[NSString stringWithFormat:@"%@,%@,%@",[UserDefaults valueForKey:@"TAccessToken"],[UserDefaults valueForKey:@"TAccessTokenSecret"],[UserDefaults valueForKey:@"TUser"]] forKey:@"bindstring"];
                }else if([[MyAppDataManager.regDic valueForKey:@"bindtype"]integerValue] == 1){
                    [pars setValue:@"facebook" forKey:@"bindto"];
                    //            [pars setValue:[NSString stringWithFormat:@"%@,%@",nil,@""] forKey:@"bindstring"];
                    [pars setValue:[NSString stringWithFormat:@"%@,%@",[UserDefaults valueForKey:@"FBAccessToken"],[UserDefaults valueForKey:@"FBUser"]] forKey:@"bindstring"];
                }
                
                
                [AppComManager getBanBuData:BanBu_Set_User_accountbind par:pars delegate:self];
                self.navigationController.view.userInteractionEnabled = NO;
            }else{
                [UserDefaults setValue:@"" forKey:@"QUser"];
                [UserDefaults setValue:@"" forKey:@"sinaUser"];
                
                BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
                delegate.logined = YES;
                //                [delegate setViewController:YES];
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"videoVerify", nil) message:NSLocalizedString(@"verifyNoticeAlert", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"wantVerify", nil), nil];
                alertView.tag = 88888;
                [alertView show];
                [alertView release];
            }
            
            
        }
        else
        {
            if([[resDic allKeys] indexOfObject:@"error"] != NSNotFound)
            {
                UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"sysNotice", nil) message:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
                alert.tag = 14142;
                [alert show];
                [alert release];
            }
        }
        
    }
}
@end
